import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
export const httpRes = {
    'Success': '200', // 请求成功
    'Fail': '1', // 请求失败
    'Exception': '2', // 系统异常
    'NoAuthorize': '3' // 没有权限
};
/**
 * 数据交互
 */
@Injectable()
export class BaHttp {
    constructor(
        private http: Http
    ) {
    }

    public post(url: string, postData: any, callback: Function): void {
        this.httpPost(url, postData, callback);
    }

    private httpPost(url: string, postData: any, callback: Function): void {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
            this.http.post(url, postData, options)
                .map(this.extractData)
                .catch(this.handleError).subscribe({
                    next: body => callback(body),
                    error: err => this.handleError(err),
                    complete: () => { },
                });
    }


    private extractData(res: Response) {
        let body = res.json() || {};
        try {
            if (body.code === httpRes.Exception) {
                console.error(body.info);
                body.info = '服务异常';
            }
        }
        catch (e) {
            console.error(e.message());
            body = {};
        }
        return body || {};
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

}